from django.template import loader, RequestContext
from django.http import HttpResponse, Http404
from django.utils import simplejson, html
from django.conf import settings
import seeker
import math

DEFAULT_PAGE_SIZES = [15, 25, 50]
DEFAULT_MEDIA_URL = settings.MEDIA_URL + '/images/seeker/'

def index( request, plugin, template_name=None, base_template=None, context_processors=None,
			page_sizes=DEFAULT_PAGE_SIZES, media_url=DEFAULT_MEDIA_URL ):
	if template_name is None:
		template_name = 'seeker/seeker.html'
	if base_template is None:
		base_template = 'search.html'
	t = loader.get_template( template_name )
	initial = plugin.get_initial_display_fields( request )
	# Build the groupings for the search field select list
	search_groups = []
	for (name,fields) in plugin.get_search_fields( request ):
		search_groups.append( (name,[{'field':f,'label':plugin.get_field_name(request,f)} for f in fields]) )
	# Build the display groupings for the select list
	display_groups = []
	field_info = []
	for (name,fields) in plugin.get_display_fields( request ):
		display_groups.append( (name,[{'field':f,'label':plugin.get_field_name(request,f),'initial':(f in initial)} for f in fields]) )
		# While we're at it, build the column model for the results table
		for field in fields:
			field_info.append( {
				'field': field,
				'label': plugin.get_field_name( request, field ),
				'type': plugin.get_field_type( request, field ),
				'formatted': plugin.is_field_formatted( request, field ),
				'sortable': plugin.is_field_sortable( request, field ),
			} )
	# Try to load the specified saved search, if possible
	try:
		search_id = request.GET['id']
		search = plugin.load_search( request, request.path, search_id )
	except Exception, ex:
		search_id = None
		search = None
	# Try to load a list of saved searches
	try:
		saved_searches = plugin.get_searches( request, request.path )
	except Exception, ex:
		saved_searches = None
	# Try to make the search_id an integer, so ifequals tag will work
	try:
		search_id = int( search_id )
	except Exception, ex:
		pass
	c = RequestContext( request, {
		'base_template': base_template,
		'search_groups': search_groups,
		'display_groups': display_groups,
		'field_info': field_info,
		'initial': initial,
		'page_sizes': page_sizes,
		'seeker_media': media_url,
		'search_url': request.path,
		'search_id': search_id,
		'search': search,
		'saved_searches': saved_searches,
	}, context_processors )
	return HttpResponse( t.render(c) )

def fieldinfo( request, plugin, **kwargs ):
	field = request.GET.get( 'field', None )
	verbose_name = plugin.get_field_name( request, field.strip() )
	if verbose_name is None:
		raise Http404()
	info = {
		'field': field,
		'name': verbose_name,
		'type': plugin.get_field_type(request,field),
		'operators': plugin.get_field_operators(request,field),
		'values': plugin.get_field_values(request,field),
		'importable': plugin.is_field_importable(request,field),
	}
	return HttpResponse( simplejson.dumps(info) )

def parse( request, plugin, **kwargs ):
	if request.method == 'POST':
		field = request.POST['field']
		data = request.FILES['datafile']['content']
		return HttpResponse( simplejson.dumps( plugin.do_import(request,field,data) ) )
	raise Http404()

def count( request, plugin, **kwargs ):
	if request.method == 'POST':
		search = seeker.Search( request.POST['search'] )
		num = plugin.do_count( request, search )
		return HttpResponse( simplejson.dumps(num) )
	raise Http404()

def render( request, plugin, **kwargs ):
	if request.method == 'POST':
		try:
			format = request.POST.get( 'format', 'json' )
			search = seeker.Search( request.POST['search'] )
			result = plugin.get_results( request, search )
			if search.sort_field is not None:
				result.sort( search.sort_field, search.is_sort_formatted() )
			page = int( request.POST.get('page',1) ) - 1
			page_size = int( request.POST.get('page_size',-1) )
			mod = __import__( 'seeker.renderers.%s' % format, None, None, ['seeker.renderers'] )
			return mod.render( request, plugin, search, result, page, page_size )
		except Exception, ex:
			print ex
	raise Http404()

def save( request, plugin, **kwargs ):
	if request.method == 'POST':
		try:
			# Trim off the "save/" part of the URL
			base_url = request.path[:-5]
			search = seeker.Search( request.POST['search'] )
			id = plugin.save_search( request, base_url, search, request.POST['name'] )
			return HttpResponse( simplejson.dumps(id) )
		except Exception, ex:
			print ex
	raise Http404()
